<?php

class PaymentController extends Controller
{
	public $layout='/layouts/column1';
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
		array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('ipn','success'),
				'users'=>array('*'),
		),
		array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','ajaxPrice'),
				'users'=>array('@'),
		),
		array('deny','users'=>array('*')),
		);
	}
	public function actionIndex()
	{
		$userData=User::model()->findbyPk(Yii::app()->user->id);
		if(empty($userData->email)||empty($userData->mobile)){
			$this->render('../default/profileIncomplete');
			return;
		}
		$p=Yii::app()->paypal;
		//$base='http://220.244.248.148:8080/yiiapp/MelbourneCoffeeReview3/index-test.php/JumpOrder/payment/';
		$p->returnUrl=$this->createAbsoluteUrl('success');
		$p->cancelUrl=$this->createAbsoluteUrl('index');
		$p->notifyUrl=$this->createAbsoluteUrl('ipn');
		$p->itemName='Jump Order Payment';
		$p->custom=Yii::app()->user->getId();
		$this->render('index',array('p'=>$p));
	}

	public function actionIpn()
	{
		$p=Yii::app()->paypal;

		if ($p->validateIpn()) {
			$payment=new PaymentTransaction('ipn');
			foreach($payment->getSafeAttributeNames() as $att){
				if(isset($_POST[$att])){
					$payment->$att=$_POST[$att];
				}
			}
			if($payment->save()){
				$p->log('Payment Saved to DB');
				$subject = 'Instant Payment Notification - Recieved Payment';
				$adminMail='msefton@jumporder.com';//msefton@seftonconsulting.com.au';
				$user=User::model()->findByPk($payment->custom);
							$mailer=Yii::app()->mailer;
		$mailer->FromName="Jump Order";
		$mailer->From=$adminMail;
		$mailer->Sender=$adminMail;
		$mailer->AddAddress($adminMail);
		$mailer->Subject = $subject;
		$mailer->getView('paymentReceived', array(
					'payment'=>$payment,
					'user'=>$user,
				));
		$mailer->Send();
				$mailer->ClearAddresses();
				$subject='Jump Order Payment Reciept';
				$recieptEmail=$payment->payer_email;
				if(!$recieptEmail){
					$recieptEmail=$user->email;
				}
				$mailer->AddAddress($recieptEmail);
		$mailer->Subject = $subject;
		$mailer->getView('paymentReciept', array(
					'payment'=>$payment,
					'user'=>$user,
				));
		$mailer->Send();
//				Yii::app()->mailer->sendOutgoingMail('paymentReciept',$recieptEmail,$subject,
//				array(
//					'payment'=>$payment,
//					'user'=>$user,
//				));
			}else{
				$p->log('Payment NOT Saved to DB: '.print_r($payment->getErrors(),true));
			}
		}
	}

	public function actionSuccess(){
		$this->render('success');
	}

}